package com.example.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/publishNews")
public class NewsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String dbUrl = "jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
        String dbUser = "root";
        String dbPassword = "204707";

        Connection conn = null;
        PreparedStatement pstmtPublish = null;
        PreparedStatement pstmtManagement = null;

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取数据库连接
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            conn.setAutoCommit(false); // 开启事务

            // 获取表单数据
            String title = request.getParameter("title");
            String category = request.getParameter("category");
            String content = request.getParameter("content");
            String author = "管理员";
            String coverImage = "default.jpg";
            String status = "已发布";
            Timestamp publishTime = new Timestamp(System.currentTimeMillis());

            // 插入新闻数据到news_publish表
            String sqlPublish = "INSERT INTO news_publish (title, category, author, publish_time, cover_image, status, content) VALUES (?, ?, ?, ?, ?, ?, ?)";
            pstmtPublish = conn.prepareStatement(sqlPublish, Statement.RETURN_GENERATED_KEYS);
            pstmtPublish.setString(1, title);
            pstmtPublish.setString(2, category);
            pstmtPublish.setString(3, author);
            pstmtPublish.setTimestamp(4, publishTime);
            pstmtPublish.setString(5, coverImage);
            pstmtPublish.setString(6, status);
            pstmtPublish.setString(7, content);

            int rowsAffectedPublish = pstmtPublish.executeUpdate();

            // 获取生成的新闻ID
            ResultSet generatedKeys = pstmtPublish.getGeneratedKeys();
            long newsId = 0;
            if (generatedKeys.next()) {
                newsId = generatedKeys.getLong(1);
            } else {
                throw new SQLException("获取新闻ID失败");
            }

            // 插入数据到news_management表
            String sqlManagement = "INSERT INTO news_management (news_id, publish_time, status) VALUES (?, ?, ?)";
            pstmtManagement = conn.prepareStatement(sqlManagement);
            pstmtManagement.setLong(1, newsId);
            pstmtManagement.setTimestamp(2, publishTime);
            pstmtManagement.setString(3, status);

            int rowsAffectedManagement = pstmtManagement.executeUpdate();

            // 提交事务
            conn.commit();

            // 返回成功响应
            PrintWriter out = response.getWriter();
            out.println("{\"status\":\"success\", \"message\":\"新闻发布成功\"}");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            sendError(response, "数据库驱动加载失败");
        } catch (SQLException e) {
            try {
                if (conn != null) {
                    conn.rollback(); // 回滚事务
                }
            } catch (SQLException rollbackEx) {
                e.printStackTrace();
            }
            sendError(response, "数据库操作失败: " + e.getMessage());
        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback(); // 回滚事务
                }
            } catch (SQLException rollbackEx) {
                e.printStackTrace();
            }
            sendError(response, "新闻发布失败: " + e.getMessage());
        } finally {
            // 关闭资源
            closeResource(pstmtManagement);
            closeResource(pstmtPublish);
            closeResource(conn);
        }
    }

    private void sendError(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("{\"status\":\"error\", \"message\":\"" + message + "\"}");
    }

    private void closeResource(AutoCloseable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}